import { defineConfig, loadEnv } from "vite";
import type { UserConfig } from "vite";
import react from "@vitejs/plugin-react";
import { fileURLToPath } from "node:url";
import viteEslint from "vite-plugin-eslint";
import postCssPxToRem from "postcss-pxtorem";
import vitePluginImp from "vite-plugin-imp";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";

export default defineConfig(({ mode }): UserConfig => {
	const env = loadEnv(mode, "./env");
	return {
		envDir: "./env",
		plugins: [
			react(),
			viteEslint({
				include: ["src/**/*.ts", "src/**/*.tsx", "src/*.ts"],
				exclude: ["./node_modules/**"],
				failOnError: true,
				cache: false
			}),
			vitePluginImp({
				libList: [
					{
						libName: "antd-mobile",
						libDirectory: "es/components",
						style(name) {
							return `antd-mobile/es/components/${name}/${name}.css`;
						}
					}
				]
			}),
			createSvgIconsPlugin({
				iconDirs: [fileURLToPath(new URL("./src/assets/svg", import.meta.url))],
				symbolId: "[name]"
			})
		],
		resolve: {
			alias: {
				"@": fileURLToPath(new URL("./src", import.meta.url))
			},
			extensions: [".js", ".ts", ".tsx", ".scss", ".css"]
		},
		css: {
			preprocessorOptions: {
				scss: {
					additionalData: `@import "@/styles/variables.scss";`
				}
			},
			postcss: {
				plugins: [
					postCssPxToRem({
						rootValue: 37.5, // 1rem的大小(设计稿宽度的1/10)
						propList: ["*"] // 需要转换的属性，这里选择全部都进行转换
					})
				]
			}
		},
		build: {
			target: "modules",
			outDir: "dist",
			assetsDir: "static",
			cssCodeSplit: true,
			sourcemap: env.VITE_PROJECT_ENV === "production" ? false : true,
			minify: "terser",
			terserOptions: {
				compress: {
					drop_console: env.VITE_PROJECT_ENV === "production",
					drop_debugger: env.VITE_PROJECT_ENV === "production"
				}
			},
			rollupOptions: {
				output: {
					chunkFileNames: "assets/js/[name]-[hash].js",
					entryFileNames: "assets/js/[name]-[hash].js",
					assetFileNames: "assets/[ext]/[name]-[hash].[ext]"
				}
			}
		},
		server: {
			port: 8080,
			open: "/",
			host: true,
			proxy: {
				"/api": {
					target: env.VITE_BASE_URL,
					changeOrigin: true,
					rewrite: path => path.replace(/^\/api/, "")
				}
			}
		}
	};
});
